/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
 *
 * Function : z = x + y
 * This sample is a very basic sample that implements vector add on Ascend plaform.
 */
#include "kernel_operator.h"
// tensor num for each queue
constexpr int32_t BUFFER_NUM = 2;

template<typename TYPE_X, typename TYPE_Y, typename TYPE_Z> class KernelAdd {
    using T = TYPE_X;
public:
    __aicore__ inline KernelAdd() {}
    __aicore__ inline void Init(GM_ADDR x, GM_ADDR y, GM_ADDR z, uint32_t smallCoreDataNum,
                                uint32_t bigCoreDataNum, uint32_t finalBigTileNum, 
                                uint32_t finalSmallTileNum, uint32_t tileDataNum, 
                                uint32_t smallTailDataNum, uint32_t bigTailDataNum, 
                                uint32_t tailBlockNum, float rtol,
                                float atol, bool equalNan) 
    {
        ASSERT(AscendC::GetBlockNum() != 0 && "block dim can not be zero!");
        uint32_t coreNum = AscendC::GetBlockIdx();
        uint32_t globalBufferIndex = bigCoreDataNum * AscendC::GetBlockIdx();
        this->tileDataNum = tileDataNum;
        this->rtol = rtol;
        this->atol = atol;
        this->equalNan = equalNan;
        if (coreNum < tailBlockNum) { 
          this->coreDataNum = bigCoreDataNum;
          this->tileNum = finalBigTileNum;
          this->tailDataNum = bigTailDataNum;
        }
        else { 
          this->coreDataNum = smallCoreDataNum;
          this->tileNum = finalSmallTileNum;
          this->tailDataNum = smallTailDataNum;
          globalBufferIndex -= (bigCoreDataNum - smallCoreDataNum) * (AscendC::GetBlockIdx() - tailBlockNum);
        }
        xGm.SetGlobalBuffer((__gm__ TYPE_X*)x + globalBufferIndex, this->coreDataNum);
        yGm.SetGlobalBuffer((__gm__ TYPE_Y*)y + globalBufferIndex, this->coreDataNum);
        zGm.SetGlobalBuffer((__gm__ int8_t*)z + globalBufferIndex, this->coreDataNum);
        pipe.InitBuffer(inQueueX, BUFFER_NUM, this->tileDataNum * sizeof(TYPE_X));
        pipe.InitBuffer(inQueueY, BUFFER_NUM, this->tileDataNum * sizeof(TYPE_Y));
        pipe.InitBuffer(outQueueZ, BUFFER_NUM, this->tileDataNum * sizeof(int8_t));
        if constexpr (std::is_same_v<T, float>) {
            pipe.InitBuffer(tmp1, this->tileDataNum * sizeof(float));
            pipe.InitBuffer(tmp2, this->tileDataNum * sizeof(half));
        } else if constexpr (std::is_same_v<T, int32_t>) {
            pipe.InitBuffer(tmp1, this->tileDataNum * sizeof(float));
            pipe.InitBuffer(tmp2, this->tileDataNum * sizeof(float));
            pipe.InitBuffer(tmp3, this->tileDataNum * sizeof(half));
        } else if constexpr (std::is_same_v<T, int32_t>){
            pipe.InitBuffer(tmp1, this->tileDataNum * sizeof(float));
            pipe.InitBuffer(tmp2, this->tileDataNum * sizeof(half));
            pipe.InitBuffer(tmp3, this->tileDataNum * sizeof(float));
        } else {
          // half
            pipe.InitBuffer(tmp1, this->tileDataNum * sizeof(half));
            pipe.InitBuffer(tmp2, this->tileDataNum * sizeof(half));
        }

        
    }
    __aicore__ inline void Process()
    {
        int32_t loopCount = this->tileNum;
        this->processDataNum = this->tileDataNum;
        for (int32_t i = 0; i < loopCount; i++) {
            if (i == this->tileNum - 1) {
              this->processDataNum = this->tailDataNum;
            }
            CopyIn(i);
            Compute(i);
            CopyOut(i);
        }
    }

private:
    __aicore__ inline void CopyIn(int32_t progress)
    {
      AscendC::LocalTensor<TYPE_X> xLocal = inQueueX.AllocTensor<TYPE_X>();
      AscendC::LocalTensor<TYPE_Y> yLocal = inQueueY.AllocTensor<TYPE_Y>();
      AscendC::DataCopy(xLocal, xGm[progress * this->tileDataNum], this->processDataNum);
      AscendC::DataCopy(yLocal, yGm[progress * this->tileDataNum], this->processDataNum);
      inQueueX.EnQue(xLocal);
      inQueueY.EnQue(yLocal);
    }
    __aicore__ inline void Compute(int32_t progress)
    {
      AscendC::LocalTensor<TYPE_X> xLocal = inQueueX.DeQue<TYPE_X>();
      AscendC::LocalTensor<TYPE_Y> yLocal = inQueueY.DeQue<TYPE_Y>();
      AscendC::LocalTensor<int8_t> zLocal = outQueueZ.AllocTensor<int8_t>();
      if constexpr (std::is_same_v<T, int8_t>) {
        auto tmpLocal1 = tmp1.Get<half>();
        auto xLocal_fp16 = tmp2.Get<half>();
        auto yLocal_fp16 = tmp3.Get<half>();

        AscendC::Cast(xLocal_fp16, xLocal, AscendC::RoundMode::CAST_NONE, this->processDataNum);
        AscendC::Cast(yLocal_fp16, yLocal, AscendC::RoundMode::CAST_NONE, this->processDataNum);
         // 计算不等式左边
        AscendC::Sub(tmpLocal1, xLocal_fp16, yLocal_fp16, this->processDataNum);
        AscendC::Abs(tmpLocal1, tmpLocal1, this->processDataNum);
        // 计算不等式右边
        AscendC::Abs(yLocal_fp16, yLocal_fp16, this->processDataNum);
        AscendC::Muls(yLocal_fp16, yLocal_fp16, (half)this->rtol, this->processDataNum);
        AscendC::Adds(yLocal_fp16, yLocal_fp16, (half)this->atol, this->processDataNum);

        AscendC::Compare(zLocal, tmpLocal1, yLocal_fp16, AscendC::CMPMODE::LE, this->processDataNum);

        AscendC::Duplicate<half>(xLocal_fp16, (half)1.0, this->processDataNum);
        AscendC::Select(xLocal_fp16, zLocal, xLocal_fp16, static_cast<half>(0), AscendC::SELMODE::VSEL_TENSOR_SCALAR_MODE, this->processDataNum);
        AscendC::Cast(zLocal, xLocal_fp16, AscendC::RoundMode::CAST_NONE, this->processDataNum);
      } else if constexpr (std::is_same_v<T, half>) {
        auto tmpLocal1 = tmp1.Get<half>();
        auto tmpLocal2 = tmp2.Get<half>();
        // 计算不等式左边
        AscendC::Sub(tmpLocal1, xLocal, yLocal, this->processDataNum);
        AscendC::Abs(tmpLocal1, tmpLocal1, this->processDataNum);
        // 计算不等式右边
        AscendC::Abs(yLocal, yLocal, this->processDataNum);
        AscendC::Muls(yLocal, yLocal, (half)this->rtol, this->processDataNum);
        AscendC::Adds(yLocal, yLocal, (half)this->atol, this->processDataNum);

        AscendC::Duplicate<half>(tmpLocal2, (half)1.0, this->processDataNum);
        AscendC::Compare(zLocal, tmpLocal1, yLocal, AscendC::CMPMODE::LE, this->processDataNum);
        AscendC::Select(tmpLocal2, zLocal, tmpLocal2, static_cast<half>(0), AscendC::SELMODE::VSEL_TENSOR_SCALAR_MODE, this->processDataNum);
        AscendC::Cast(zLocal, tmpLocal2, AscendC::RoundMode::CAST_NONE, this->processDataNum);
      } else if constexpr (std::is_same_v<T, int32_t>) {
        auto xLocal_fp32 = tmp1.Get<float>();
        auto tmpLocal2 = tmp2.Get<half>();
        auto yLocal_fp32 = tmp3.Get<float>();
        
        AscendC::Cast(xLocal_fp32, xLocal, AscendC::RoundMode::CAST_NONE, this->processDataNum);
        AscendC::Cast(yLocal_fp32, yLocal, AscendC::RoundMode::CAST_NONE, this->processDataNum);

        // 计算不等式左边
        AscendC::Sub(xLocal_fp32, xLocal_fp32, yLocal_fp32, this->processDataNum);
          // Abs不支持int32_t
        AscendC::Abs(xLocal_fp32, xLocal_fp32, this->processDataNum);
        // 计算不等式右边
        AscendC::Abs(yLocal_fp32, yLocal_fp32, this->processDataNum);
        AscendC::Muls(yLocal_fp32, yLocal_fp32, this->rtol, this->processDataNum);
        AscendC::Adds(yLocal_fp32, yLocal_fp32, this->atol, this->processDataNum);

        AscendC::Compare(zLocal, xLocal_fp32, yLocal_fp32, AscendC::CMPMODE::LE, this->processDataNum);
        AscendC::Duplicate<half>(tmpLocal2, (half)1.0, this->processDataNum);
        AscendC::Select(tmpLocal2, zLocal, tmpLocal2, static_cast<half>(0), AscendC::SELMODE::VSEL_TENSOR_SCALAR_MODE, this->processDataNum);
        AscendC::Cast(zLocal, tmpLocal2, AscendC::RoundMode::CAST_NONE, this->processDataNum);
      }
      else if constexpr (std::is_same_v<T, float>){
        auto tmpLocal1 = tmp1.Get<float>();
        auto tmpLocal2 = tmp2.Get<half>();
        // 计算不等式左边
        AscendC::Sub(tmpLocal1, xLocal, yLocal, this->processDataNum);
        AscendC::Abs(tmpLocal1, tmpLocal1, this->processDataNum);
        // 计算不等式右边
        AscendC::Abs(yLocal, yLocal, this->processDataNum);
        AscendC::Muls(yLocal, yLocal, this->rtol, this->processDataNum);
        AscendC::Adds(yLocal, yLocal, this->atol, this->processDataNum);

        AscendC::Compare(zLocal, tmpLocal1, yLocal, AscendC::CMPMODE::LE, this->processDataNum);
        AscendC::Duplicate<half>(tmpLocal2, (half)1.0, this->processDataNum);
        AscendC::Select(tmpLocal2, zLocal, tmpLocal2, static_cast<half>(0), AscendC::SELMODE::VSEL_TENSOR_SCALAR_MODE, this->processDataNum);
        AscendC::Cast(zLocal, tmpLocal2, AscendC::RoundMode::CAST_NONE, this->processDataNum);
      }
      outQueueZ.EnQue<int8_t>(zLocal);
      inQueueX.FreeTensor(xLocal);
      inQueueY.FreeTensor(yLocal);
    }
    __aicore__ inline void CopyOut(int32_t progress)
    {
      AscendC::LocalTensor<int8_t> zLocal = outQueueZ.DeQue<int8_t>();  
      AscendC::DataCopy(zGm[progress * this->tileDataNum], zLocal, this->processDataNum);
      outQueueZ.FreeTensor(zLocal);
    }

private:
    AscendC::TPipe pipe;
    AscendC::TQue<AscendC::QuePosition::VECIN, BUFFER_NUM> inQueueX, inQueueY;
    AscendC::TQue<AscendC::QuePosition::VECOUT, BUFFER_NUM> outQueueZ;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> tmp1, tmp2, tmp3;
    AscendC::GlobalTensor<TYPE_X> xGm;
    AscendC::GlobalTensor<TYPE_Y> yGm;
    AscendC::GlobalTensor<int8_t> zGm;
    uint32_t coreDataNum;
    uint32_t tileNum;
    uint32_t tileDataNum;
    uint32_t tailDataNum;
    uint32_t processDataNum;
    float atol;
    float rtol;
    bool equalNan;
};


extern "C" __global__ __aicore__ void is_close(GM_ADDR x1, GM_ADDR x2, GM_ADDR y, GM_ADDR workspace, GM_ADDR tiling) {
    GET_TILING_DATA(tiling_data, tiling);
    KernelAdd<DTYPE_X1, DTYPE_X2, DTYPE_Y> op;
    op.Init(x1, x2, y, tiling_data.smallCoreDataNum, 
            tiling_data.bigCoreDataNum, tiling_data.finalBigTileNum, 
            tiling_data.finalSmallTileNum, tiling_data.tileDataNum, 
            tiling_data.smallTailDataNum, tiling_data.bigTailDataNum, 
            tiling_data.tailBlockNum, tiling_data.rtol,
            tiling_data.atol, tiling_data.equalNan);  
    op.Process();
}